package com.kkb.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.activation.DataSource;
import java.sql.Connection;

@Configuration
@PropertySource({"classpath:jdbc.properties"})
public class JDBCConfig {
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    /**
     * 配置数据源
     */
    @Bean("druidDataSource")
    public DataSource createDataSource(){
        //创建Druid对象
        DruidDataSource dataSource = new DruidDataSource();
        //配置驱动,url,⽤户名,密码
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return (DataSource) dataSource;
    }
    /**
     * 配置连接对象
     */
    @Bean("connection")
    public Connection createConnection(@Qualifier("druidDataSource") DataSource dataSource){
        //开启 事务Connection对象与 MybatisConnection对象同步
        TransactionSynchronizationManager.initSynchronization();
        //获取Connection对象
        Connection connection = DataSourceUtils.getConnection((javax.sql.DataSource) dataSource);
        return connection;
    }
}
